<template>
	<div class="worktime-container">
		<el-tabs v-model="activeName" @tab-click="handleClick">
			<el-tab-pane label="工作日规则" name="worktime">
				<Search @searchData="searchData" />
				<div class="head">
					<el-button type="primary" @click="addWorking">新增</el-button>
				</div>
				<Table :tableData="tableData">
					<template v-slot:btn>
						<el-table-column width="310px" align="center" label="操作">
							<template slot-scope="scope">
								<el-button v-if="scope.row.name !== '全年无休'" size="mini" class="set-btn" @click="showEditWorkingDays(scope.$index, scope.row)">编辑</el-button>
								<el-button size="mini" class="set-btn" @click="showDetailsWorkingDays(scope.$index, scope.row)">详情</el-button>
							</template>
						</el-table-column>
					</template>
				</Table>
				<PageSize class="page" :pages="selectWorkingDaysList.pages" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
			</el-tab-pane>
		</el-tabs>
		<AddWorkingDays
			v-if="showAddWorkingDays"
			:defaultWorkingName="defaultWorkingName"
			:titleWorkingDays="titleWorkingDays"
			:showSyncBtn="showSyncBtn"
			:showAddWorkingDays="showAddWorkingDays"
			:inputDisabled="inputDisabled"
			:calendarDaySelected="calendarDaySelected"
			:showCalendar="showCalendar"
			:showDetailsBtn="showDetailsBtn"
			@handleClose="handleClose"
			@clearWorkingDays="clearWorkingDays"
			@syncData="syncData"
			@submitWorkingDays="submitWorkingDays"
		></AddWorkingDays>
	</div>
</template>

<script>
import Table from '@/views/components/Table.vue';
import PageSize from '@/views/components/PageSize.vue';
import AddWorkingDays from '../components/AddWorkingDays.vue';
import Search from './components/Search.vue';
import { getWorkingDaysList, setWorkingDays, getWorkingDates, modifyWorkingDays, syncWorkingDays } from '../../api/api';
import { mapMutations, mapState } from 'vuex';
export default {
	components: {
		AddWorkingDays,
		Table,
		PageSize,
		Search
	},
	data() {
		return {
			//查询工作日列表
			selectWorkingDaysList: {
				name: '',
				startTime: '',
				endTime: '',
				username: '',
				pages: { page: 1, pageSize: 10, total: 0 }
			},
			showAddWorkingDays: false, //新增工作日规则组件状态
			calendarDaySelected: false, //日历组件可选与不可选状态
			showCalendar: false, //日历显示与隐藏
			showSyncBtn: false, //同步按钮显示与隐藏
			titleWorkingDays: '', //弹窗标题
			defaultWorkingName: '', //输入框默认值
			inputDisabled: false, //输入框禁止状态
			activeName: 'worktime', //表单model
			workingDaysId: '', //工作日id
			showDetailsBtn: false, //清空与确定按钮显示与隐藏
			tableData: {
				sort: false,
				tableHead: [
					{
						label: '规则名称',
						prop: 'name'
					},
					{
						label: '创建时间',
						prop: 'createdAt'
					},
					{
						label: '创建人ID',
						prop: 'userName'
					}
				],
				tableConent: [], //工作日列表数据
				showIndex: true,
				showCheck: false
			},
			form: {
				createPersonId: '',
				startTime: '',
				endTime: '',
				name: ''
			},
			pickerOptions: {
				shortcuts: [
					{
						text: '今天',
						onClick(picker) {
							picker.$emit('pick', new Date());
						}
					},
					{
						text: '昨天',
						onClick(picker) {
							const date = new Date();
							date.setTime(date.getTime() - 3600 * 1000 * 24);
							picker.$emit('pick', date);
						}
					},
					{
						text: '一周前',
						onClick(picker) {
							const date = new Date();
							date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
							picker.$emit('pick', date);
						}
					}
				]
			}
		};
	},
	computed: {
		...mapState({
			saveDates: state => state.calendar.saveDates
		})
	},
	mounted() {
		this.getWorkingDays();
	},
	methods: {
		...mapMutations('calendar', ['SAVE_DATES', 'SELECT_NOW_DAY_BY_YEAR', 'SET_SELECT_YEAR']),
		//获取工作日列表方法
		getWorkingDays() {
			let data = {
				...this.selectWorkingDaysList,
				...this.selectWorkingDaysList.pages
			};
			getWorkingDaysList(data)
				.then(res => {
					console.log(res);
					if (res.status === 200) {
						this.selectWorkingDaysList.pages.total = res.data.result.count;
						this.tableData.tableConent = res.data.result.rows.map(item => {
							return {
								id: item.id,
								name: item.name,
								createdAt: this.$moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
								userName: item.user && item.user.userName ? item.user.userName : '-'
							};
						});
					}
				})
				.catch(err => {
					// this.$message.error(`获取工作日失败${err.message}`);
					console.log(err);
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},
		//检索
		searchData(data) {
			this.selectWorkingDaysList.pages.page = 1;
			this.selectWorkingDaysList.pages.pageSize = 10;
			let workingDaysData = {
				page: this.selectWorkingDaysList.pages.page,
				pageSize: this.selectWorkingDaysList.pages.pageSize,
				name: data.name,
				startTime: data.startTime,
				endTime: data.endTime,
				username: data.createPersonId
			};
			getWorkingDaysList(workingDaysData)
				.then(res => {
					console.log(res);
					if (res.status === 200) {
						this.selectWorkingDaysList.pages.total = res.data.result.count;
						this.tableData.tableConent = res.data.result.rows.map(item => {
							return {
								id: item.id,
								name: item.name,
								createdAt: this.$moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
								userName: item.user && item.user.userName ? item.user.userName : '-'
							};
						});
					} else {
						this.$message.error('检索工作日列表失败');
					}
				})
				.catch(err => {
					this.$message.error(`获取工作日失败${err.message}`);
					console.log(err);
				});
		},
		//查看工作日规则方法
		setWorkingDays(id) {
			getWorkingDates(id)
				.then(res => {
					console.log(res.data);
					if (res.status === 200 && res.data.data.workDayDates.length !== 0) {
						let arrWorking = res.data.data.workDayDates.map(datas => {
							return {
								year: Number(datas.date.split('-')[0]),
								month: Number(datas.date.split('-')[1]),
								day: Number(datas.date.split('-')[2])
							};
						});
						this.$store.commit('SELECT_NOW_DAY_BY_YEAR', arrWorking);
						this.$store.commit('SAVE_DATES', arrWorking);
						this.showCalendar = true;
					}
				})
				.catch(err => {
					this.$message.error(`查询工作日失败${err.message}`);
					console.log(err);
				});
		},
		changePageSize(val) {
			this.selectWorkingDaysList.pages.pageSize = val;
			this.selectWorkingDaysList.pages.page = 1;
			this.getWorkingDays();
		},
		changeCurrentPage(val) {
			this.selectWorkingDaysList.pages.page = val;
			// this.selectWorkingDaysList.pages.pageSize = 10;
			this.getWorkingDays();
		},
		//取消按钮
		handleClose() {
			this.showAddWorkingDays = false;
		},
		//清空工作日
		clearWorkingDays(years) {
			this.$confirm(`你确定要清空${years}年的休息日设定吗？`, '温馨提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.$store.commit('SAVE_DATES', []);
					this.$store.commit('SELECT_NOW_DAY_BY_YEAR', []);
					this.$message({
						type: 'success',
						message: '清空工作日成功!'
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '清空工作日失败'
					});
				});
		},
		//同步外系统的工作日数据 years:需要同步的年份
		syncData(years) {
			this.$confirm('同步工作日模板后，当前编辑的工作日规则将被覆盖，是否确定继续同步', '温馨提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					//同步外系统的工作日数据
					syncWorkingDays(years)
						.then(res => {
							if (res.status === 200) {
								let syncNowYearDays = res.data.data.map(datas => {
									return {
										year: Number(datas.split('-')[0]),
										month: Number(datas.split('-')[1]),
										day: Number(datas.split('-')[2])
									};
								});
								this.$store.commit('SELECT_NOW_DAY_BY_YEAR', syncNowYearDays);
								this.$store.commit('SAVE_DATES', syncNowYearDays);
								this.$message({
									type: 'success',
									message: '同步工作日成功!'
								});
							} else {
								this.$message.error('同步工作日失败');
							}
						})
						.catch(err => {
							this.$message.error(`同步工作日失败${err}`);
							console.log(err);
						});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消同步工作日'
					});
				});
		},
		//提交工作日数据 name:工作日规则名称
		submitWorkingDays(name) {
			let data = {};
			data.name = name;
			data.dates = [];
			this.saveDates.forEach(calendar => {
				let { year, month, day } = calendar;
				if (day < 10) {
					day = '0' + day;
				}
				let date = year + '-' + month + '-' + day;
				data.dates.push(date);
			});
			if (this.workingDaysId === '') {
				//新增工作日规则
				setWorkingDays(data)
					.then(res => {
						if (res.status === 200) {
							this.getWorkingDays();
							this.showAddWorkingDays = false;
							this.$message.success('新增成功');
						} else {
							this.$message.error('新增失败');
						}
					})
					.catch(err => {
						this.$message.error(`新增失败${err.message}`);
						console.log(err);
					});
			} else {
				//修改工作日规则
				modifyWorkingDays(this.workingDaysId, data)
					.then(res => {
						console.log(res);
						if (res.status === 200) {
							this.getWorkingDays();
							this.showAddWorkingDays = false;
							this.$message.success('修改成功！');
						} else {
							this.$message.error('修改失败');
						}
					})
					.catch(err => {
						this.$message.error(`修改失败${err.message}`);
						console.log(err);
					});
			}
		},
		//新增工作日规则
		addWorking() {
			this.$store.commit('SAVE_DATES', []);
			this.$store.commit('SELECT_NOW_DAY_BY_YEAR', []);
			this.showAddWorkingDays = true;
			this.showSyncBtn = true;
			this.titleWorkingDays = '新增工作日规则';
			this.inputDisabled = false;
			this.defaultWorkingName = '';
			this.calendarDaySelected = false;
			this.showCalendar = true;
			this.workingDaysId = '';
			this.showDetailsBtn = true;
		},
		//编辑工作日规则
		showEditWorkingDays(index, row) {
			this.$store.commit('SAVE_DATES', []);
			this.$store.commit('SELECT_NOW_DAY_BY_YEAR', []);
			this.showAddWorkingDays = true;
			this.showSyncBtn = false;
			this.titleWorkingDays = '编辑工作日规则';
			this.defaultWorkingName = row.name;
			this.setWorkingDays(row.id);
			this.workingDaysId = row.id;
			this.calendarDaySelected = false;
			this.inputDisabled = false;
			this.showDetailsBtn = true;
			this.showCalendar = true;
		},
		//查看工作日规则
		showDetailsWorkingDays(index, row) {
			this.$store.commit('SAVE_DATES', []);
			this.$store.commit('SELECT_NOW_DAY_BY_YEAR', []);
			this.showAddWorkingDays = true;
			this.showSyncBtn = false;
			this.titleWorkingDays = row.name;
			this.defaultWorkingName = row.name;
			this.calendarDaySelected = true;
			this.setWorkingDays(row.id);
			this.inputDisabled = true;
			this.showCalendar = true;
			this.showDetailsBtn = false;
		}
	}
};
</script>

<style lang="less" scoped>
.worktime-container {
	.head {
		padding-bottom: 20px;
		.el-button {
			width: 84px;
			height: 36px;
			background-color: #6384fe;
			padding: 0;
		}
	}
	.set-btn {
		color: #fff;
		background-color: #6384fe;
	}
	.page {
		margin-top: 15px;
	}
}
</style>

<style lang="less" scoped>
.search-container {
	height: 100px;
	.el-form {
		display: flex;
		.el-form-item {
			padding-right: 18px;
		}

		.btn {
			padding: 0;
			.el-button {
				height: 34px;
				width: 64px;
				padding: 0;
				border: 1px solid #6384fe;
				color: #6384fe;
			}
		}
	}
}
</style>

<style lang="less">
.search-container {
	.el-form-item {
		label {
			padding: 0;
		}
		input {
			height: 34px;
		}
	}
	.btn {
		.el-form-item__content {
			line-height: 120px;
		}
	}
	.line {
		text-align: center;
		padding: 0 10px;
	}
}
</style>
